class ActiveUser < ActiveRecord::Base
    belongs_to :user
  
  #Active ActiveUser Portal Controller
  
  def create_user(params_for_user,params_for_profile)
    puts params_for_user
    new_user = User.new(params_for_user)
    puts new_user.search_tag
    puts new_user.password
    new_user.created_ip=self.active_user_ip
    new_user.profile = Profile.new(params_for_profile)
    return new_user
  end
  
  def create_company(params_for_company)
    return user.banned? ? nil : user.create_company(params_for_company)
  end
  
  def create_incumbent(params,company)
    return user.banned? ? nil : user.create_incumbent(params,company)
  end
  
  def create_topic(params,forum)
    return user.banned? ? nil : user.create_topic(params,forum)
  end
  
  def create_picture(params,obj_id)
    return user.create_picture(params,obj_id)
  end
  
  def delete_picture(id)
    return user.delete_picture(id)
  end
  
  def update_topic(params,topic)
    return user.update_topic(params,topic)
  end
  
  def create_comment(params,obj)
    return user.banned? ? nil : user.create_comment(params,obj,self.active_user_ip)
  end
  
  def update_comment(params,comment)
    return user.update_comment(params,comment)
  end
  
  def guest?
    return user_id == GUEST_USER_ID
  end
  
  def adminstrative?
    user=User.find_by_id(self.user_id)
    return user.administrative?
  end
  
  def try_to_login(params)
    user = User.login(params[:name], params[:password])
    unless user.nil?
      user.after_login_success(self)
      return true
    else
      return false
    end
  end
  
  def create_query_conditions(query,category_id,additional_conditions="")
    User.find_by_id(self.user_id).create_query_conditions(query,category_id,additional_conditions)
  end
  
  def validate_active_user(user_ip)
    unless self.active_user_ip==user_ip
      self.user_id=GUEST_USER_ID
      self.active_user_ip=user_ip
    end
    self.last_active_at=Time.now
    self.save
  end
  
  def log_action(control_name,action_name,obj_id)
    self.last_obj_id=obj_id
    self.last_control=control_name
    self.last_action=action_name
    self.user.log_action(control_name,action_name,obj_id)
    self.save
  end
  
  def self.active_user(active_user_id,user_ip)
    if activeuser=ActiveUser.find_by_id(active_user_id)
      activeuser.validate_active_user(user_ip)
    else
      activeuser=ActiveUser.create(:active_user_ip=>user_ip,
                                   :user_id=>GUEST_USER_ID,
                                   :last_active_at=>Time.now)
    end
    return activeuser
  end
  
  def self.remove_active_user(active_user_id)
    if activeuser=ActiveUser.find_by_id(active_user_id)
      unless activeuser.guest?
        User.find_by_id(activeuser.user_id).logout 
      end
      activeuser.destroy
    end
  end
end
